<template>
  <div class="mod-config">
    <el-form>
      <el-form-item>
        <el-button size="mini" v-if="isAuth('goods:goodssupplier:save')" type="primary" @click="addOrUpdateHandle()">新增
        </el-button>
        <el-button size="mini" v-if="isAuth('goods:goodssupplier:delete')" type="danger" @click="deleteHandle()"
          :disabled="dataListSelections.length <= 0">批量删除</el-button>
      </el-form-item>
    </el-form>
    <el-divider></el-divider>
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item>
        <el-input size="mini" v-model="dataForm.key" placeholder="参数名" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="mini" @click="getDataList()" type="success"  >查询</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="dataList"
      @cell-dblclick="tableDbEdit"
      @selection-change="selectionChangeHandle"
      border size="mini"
      v-loading="dataListLoading"
      style="width: 100%;"
      :header-cell-style="{ background: '#fcfcfc', color: '#606266', height:'36px'}">
      <el-table-column type="selection" header-align="center" align="center" width="50">
      </el-table-column>
      <el-table-column type="index" header-align="center" align="center" width="50" label="序号">
      </el-table-column>
      <el-table-column prop="supllierType" width="120" header-align="center" align="center" label="类型">
      </el-table-column>
      <el-table-column prop="supplierName" width="220"  header-align="center" align="center" label="名称">
        <template slot-scope="scope">
           <el-input size="mini" v-model="scope.row.supplierName" v-if="showInput == `supplierName${scope.row.supplierId}`"
             @blur='blurInput(scope.row, "supplierName", scope.row.supplierName)' v-focus>
           </el-input>
           <span v-else>{{scope.row.supplierName}}</span>
         </template>
      </el-table-column>
      <el-table-column prop="address" width="260" header-align="center" align="center" label="地址">
        <template slot-scope="scope">
           <el-input size="mini" v-model="scope.row.address" v-if="showInput == `address${scope.row.supplierId}`"
             @blur='blurInput(scope.row, "address", scope.row.address)' v-focus>
           </el-input>
           <span v-else>{{scope.row.address}}</span>
         </template>
      </el-table-column>
      <el-table-column prop="salesman" header-align="center" align="center" label="销售人员">
        <template slot-scope="scope">
           <el-input size="mini" v-model="scope.row.salesman" v-if="showInput == `salesman${scope.row.supplierId}`"
             @blur='blurInput(scope.row, "salesman", scope.row.salesman)' v-focus>
           </el-input>
           <span v-else>{{scope.row.salesman}}</span>
         </template>
      </el-table-column>
      <el-table-column prop="tel" width="120" header-align="center" align="center" label="电话">
        <template slot-scope="scope">
           <el-input type="number" size="mini" v-model="scope.row.tel" v-if="showInput == `tel${scope.row.supplierId}`"
             @blur='blurInput(scope.row, "tel", scope.row.tel)' v-focus>
           </el-input>
           <span v-else>{{scope.row.tel}}</span>
         </template>
      </el-table-column>
      <el-table-column prop="mobile" width="120" header-align="center" align="center" label="手机">
        <template slot-scope="scope">
           <el-input size="mini" type="number" v-model="scope.row.mobile" v-if="showInput == `mobile${scope.row.supplierId}`"
             @blur='blurInput(scope.row, "mobile", scope.row.mobile)' v-focus>
           </el-input>
           <span v-else>{{scope.row.mobile}}</span>
         </template>
      </el-table-column>
      <el-table-column prop="status" header-align="center" align="center" label="状态">
        <template slot-scope="scope">
          <el-switch size="mini" v-model="scope.row.status" @change="saveHandle(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="corporater" header-align="center" align="center" label="法人代表">
        <template slot-scope="scope">
           <el-input size="mini" v-model="scope.row.corporater" v-if="showInput == `corporater${scope.row.supplierId}`"
             @blur='blurInput(scope.row, "corporater", scope.row.corporater)' v-focus>
           </el-input>
           <span v-else>{{scope.row.corporater}}</span>
         </template>
      </el-table-column>
      <el-table-column prop="businessLicense" width="120" header-align="center" align="center" label="营业执照">
        <template slot-scope="scope">
          <el-image  v-for="(item,i) in scope.row.licenses" class="col-image" @click="handleImgPreview(item,i)" :key="i" :src="item"  ></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="businessTimeLimit" width="120"  header-align="center" align="center" label="营业执照期限">
        <template slot-scope="scope">
           <el-input size="mini" v-model="scope.row.businessTimeLimit" v-if="showInput == `businessTimeLimit${scope.row.supplierId}`"
             @blur='blurInput(scope.row, "businessTimeLimit", scope.row.businessTimeLimit)' v-focus>
           </el-input>
           <span v-else>{{scope.row.businessTimeLimit}}</span>
         </template>
      </el-table-column>
      <el-table-column prop="productBusinessLlicense" width="120" header-align="center" align="center" label="产品经营许可证">
        <template slot-scope="scope">
          <el-image  v-for="(item,i) in scope.row.productCerts" class="col-image" @click="handleImgPreview(item,i)" :key="i" :src="item"  ></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="productTimeLimit" width="140"  header-align="center" align="center" label="产品经营许可证期限">
        <template slot-scope="scope">
           <el-input size="mini" v-model="scope.row.productTimeLimit" v-if="showInput == `productTimeLimit${scope.row.supplierId}`"
             @blur='blurInput(scope.row, "productTimeLimit", scope.row.productTimeLimit)' v-focus>
           </el-input>
           <span v-else>{{scope.row.productTimeLimit}}</span>
         </template>
      </el-table-column>
      <el-table-column prop="leader" header-align="center" align="center" label="负责人">
        <template slot-scope="scope">
           <el-input size="mini" v-model="scope.row.leader" v-if="showInput == `leader${scope.row.supplierId}`"
             @blur='blurInput(scope.row, "leader", scope.row.leader)' v-focus>
           </el-input>
           <span v-else>{{scope.row.leader}}</span>
         </template>
      </el-table-column>
      <el-table-column prop="organizationCode" width="120" header-align="center" align="center" label="组织机构代码">
        <template slot-scope="scope">
           <el-input size="mini" v-model="scope.row.organizationCode" v-if="showInput == `organizationCode${scope.row.supplierId}`"
             @blur='blurInput(scope.row, "organizationCode", scope.row.organizationCode)' v-focus>
           </el-input>
           <span v-else>{{scope.row.organizationCode}}</span>
         </template>
      </el-table-column>
      <el-table-column prop="organizationTimeLimit" width="120"  header-align="center" align="center" label="组织机构期限">
        <template slot-scope="scope">
           <el-input size="mini" v-model="scope.row.organizationTimeLimit" v-if="showInput == `organizationTimeLimit${scope.row.supplierId}`"
             @blur='blurInput(scope.row, "organizationTimeLimit", scope.row.organizationTimeLimit)' v-focus>
           </el-input>
           <span v-else>{{scope.row.organizationTimeLimit}}</span>
         </template>
      </el-table-column>
      <el-table-column prop="taxNumber" header-align="center" align="center" label="税务号">
        <template slot-scope="scope">
           <el-input size="mini" v-model="scope.row.taxNumber" v-if="showInput == `taxNumber${scope.row.supplierId}`"
             @blur='blurInput(scope.row, "taxNumber", scope.row.taxNumber)' v-focus>
           </el-input>
           <span v-else>{{scope.row.taxNumber}}</span>
         </template>
      </el-table-column>
      <el-table-column prop="createTime" width="140" header-align="center" align="center" label="创建时间">
      </el-table-column>
      <el-table-column prop="updateTime" width="140" header-align="center" align="center" label="修改时间">
      </el-table-column>
      <el-table-column prop="remark" header-align="center" align="center" label="备注">
      </el-table-column>
      <el-table-column fixed="right" header-align="center" align="center" width="150" label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="saveHandle(scope.row)">保存</el-button>
          <el-button size="mini" type="text" @click="addOrUpdateHandle(scope.row.supplierId)">修改</el-button>
          <el-button size="mini" type="text" @click="deleteHandle(scope.row.supplierId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>

    <!-- 图片预览对话框 -->
    <el-dialog v-drag title="图片预览" :visible.sync="imgDialogVisible" width="50%">
      <el-image style="width: 100%;" @close="handCloseImgDialog" :src="previewPath" ></el-image>
    </el-dialog>

  </div>
</template>

<script>
  import AddOrUpdate from './goodssupplier-add-or-update'
  export default {
    data() {
      return {
        dataForm: {
          key: ''
        },
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        showInput: "",
        oldData: {},
        currentData: {},
        previewPath:'',
        imgDialogVisible: false
      }
    },
    components: {
      AddOrUpdate
    },
    activated() {
      this.getDataList()
    },
    methods: {
      // 获取数据列表
      getDataList() {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/goods/goodssupplier/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'key': this.dataForm.key
          })
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list
            this.dataList.forEach(item => {
              item.status = item.status == 1 ? true : false

              if(item.businessLicense){
                item.licenses = item.businessLicense.split(",")
              }else{
                item.licenses = []
              }

              if(item.productBusinessLlicense){
                item.productCerts = item.productBusinessLlicense.split(",")
              }else{
                item.productCerts = []
              }
            })
            this.totalPage = data.page.totalCount
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      // 每页数
      sizeChangeHandle(val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle(val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle(val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle(supplierId) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(supplierId)
        })
      },
      async saveHandle(row){
        row.status = row.status ? 1 : 0
        const res = await this.$http({
             url:`/goods/goodssupplier/update`,
             method: 'post',
             data: this.$http.adornData(row)
        });
        let data = res.data
        if (data && data.code !== 0) {
          row.status = !row.status;
          return this.$message.error('修改失败!');
        }
        this.$message.success('更新成功！');
        this.getDataList();
      },
      // 删除
      deleteHandle(supplierId) {
        var ids = supplierId ? [supplierId] : this.dataListSelections.map(item => {
          return item.supplierId
        })
        this.$confirm(`确定对[supplierId=${ids.join(',')}]进行[${supplierId ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/goods/goodssupplier/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({
            data
          }) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },
      // 当input失去光标后进行的操作
      async blurInput(row, name, value) {
        // 判断数据是否有所改变，如果数据有改变则调用修改接口
        if (this.oldData[name] != value) {
          row[name] = value
          if(value === true){
            row[name] = 1
          }else if(value === false){
            row[name] = 0
          }
        }
        this.showInput = ""
        this.currentData = row
      },
      handleImgPreview(url, i) {
        console.log(url)
        this.previewPath = url
        this.imgDialogVisible = true
      },
      handCloseImgDialog(){
        this.previewPath = ''
        this.imgDialogVisible = false
      },
      /*
      方法参数皆为框架方法的默认传参
      row     行数据
      column  被点击的触发了方法的单元格
      event   事件
      */
      tableDbEdit(row, column, event) {
        this.showInput = column.property + row.supplierId
        this.oldData[column.property] = row[column.property]
      }
    },
    directives: {
      // 通过自定义指令实现的表单自动获得光标的操作
      focus: {
        inserted: function(el) {
          if (el.tagName.toLocaleLowerCase() == "input") {
            el.focus()
          } else {
            if (el.getElementsByTagName("input")) {
              el.getElementsByTagName("input")[0].focus()
            }
          }
          el.focus()
        }
      },
      focusTextarea: {
        inserted: function(el) {
          if (el.tagName.toLocaleLowerCase() == "textarea") {
            el.focus()
          } else {
            if (el.getElementsByTagName("textarea")) {
              el.getElementsByTagName("textarea")[0].focus()
            }
          }
          el.focus()
        }
      }
    },
  }
</script>
